<template>
  <div class="h-full flex flex-col overflow-auto">
    <ReadCard ref="readCardRef" business-type="门诊收费" :call-back-data="formState" @read="readSuccess" @tab-change="tabChange">
      <template #extra>
        <div class="flex items-center">
          <div class="font-bold">挂号时间：</div>
          <div class="flex">
            <a-date-picker v-model:value="formState.stdate" placeholder="开始时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            <a-date-picker v-model:value="formState.eddate" class="ml-2" placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </div>
        </div>
      </template>
      <template #selfCost>
        <!-- <a-card> -->
        <a-form ref="formRef" :model="formState" class="flex justify-between form-style-flex">
          <div class="flex">
            <a-form-item name="brName" class="w-[260px] mr-3 !mb-0">
              <SelectTable
                v-model:value="formState.brName"
                :search-params="{ stdate: formState.stdate, eddate: formState.eddate, type: '2', cxtype: 'zf' }"
                type="门诊挂号患者列表"
                placeholder="姓名/助记码/卡号/手机号/身份证号"
                @select="onSelect"
              />
            </a-form-item>
            <a-form-item label="挂号时间" class="!mb-0">
              <div class="flex">
                <a-date-picker v-model:value="formState.stdate" placeholder="开始时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                <a-date-picker v-model:value="formState.eddate" class="ml-2" placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
              </div>
            </a-form-item>
          </div>

          <div>
            <a-button class="mr-2" @click="onClickReset">重置</a-button>
            <a-button type="primary" @click="onClickRefresh">刷新</a-button>
          </div>
        </a-form>
        <!-- </a-card> -->
      </template>
      <template v-if="tabActiveKey !== '自费'" #rightBtn>
        <div class="flex flex-wrap justify-end items-center" :class="isSmallScreen ? 'w-[120px]' : 'w-[320px]'">
          <div class="flex">
            <span class="mr-2 font-bold">医保结算</span>
            <a-switch v-model:checked="formState.settlementType" class="mr-4" />
          </div>
          <div class="flex">
            <a-button class="mx-2" @click="onClickReset">重置</a-button>
            <a-button type="primary" @click="onClickRefresh">刷新</a-button>
          </div>
        </div>
      </template>
    </ReadCard>
    <PatientInfoHeader :patient-info="patientInfo" :show-insurance="tabActiveKey !== '自费'" class="mt-2" @change="getOutpInfo">
      <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
      <div>
        <div class="flex items-center">
          <LabelValue label="卡号" :value="patientInfo.brId" :width="160" label-class="w-[52px] text-right" />
          <LabelValue label="病案号" :value="patientInfo[isBGMSG ? 'brBlkh' : 'oprSn']" :width="160" />
          <LabelValue label="科室" :value="patientInfo.ksmc" :width="160" />
          <LabelValue label="类别" :value="patientInfo.ghlb" :width="160" />
        </div>
        <div class="flex items-center">
          <LabelValue label="门诊号" :value="patientInfo.jzbh" :width="160" />
          <LabelValue label="病历号" :value="patientInfo[isBGMSG ? 'oprSn' : 'brBlkh']" :width="160" />
          <LabelValue label="医生" :value="patientInfo.empName" :width="160" />
          <LabelValue label="时间" :value="patientInfo.ghsj" :width="200" />
        </div>
      </div>
    </PatientInfoHeader>
    <div class="mt-2 flex flex-1 overflow-hidden">
      <div class="w-3/5 mr-2 relative overflow-auto">
        <a-card>
          <div class="flex justify-between items-center mb-2">
            <div class="flex items-center">
              <BaseTitle title="收费明细" class="">
                <div class="ml-4 flex items-center">
                  <span class="font-normal pr-2">处置</span>
                  <a-switch v-model:checked="czFlag" :disabled="!jzbh" @change="onClickRefresh()" />
                  <span class="font-normal pr-2 ml-2">处方</span>
                  <a-switch v-model:checked="cfFlag" :disabled="!jzbh" @change="onChangeCfSwitch" />
                  <a-select
                    v-if="cfFlag"
                    v-model:value="cfbhList"
                    :max-tag-count="3"
                    :disabled="!jzbh"
                    mode="multiple"
                    placeholder="请选择"
                    :options="cfbhData"
                    allow-clear
                    class="ml-2 w-[260px]"
                    @change="onClickRefresh()"
                  />
                </div>
              </BaseTitle>
            </div>
            <div class="flex">
              <div class="ml-4 flex items-center">
                <span class="font-normal pr-2">显示套餐</span>
                <a-switch v-model:checked="packageSwitch" :disabled="!tableDataDetail.length" @change="onClickRefresh()" />
              </div>
              <div v-if="tabActiveKey !== '自费' && tabActiveKey !== '特殊人员'" class="flex ml-4">
                <a-button type="primary" @click="onRxUpload(false, 3, '', 'upload')"> 处方上传 </a-button>
                <a-button class="ml-2" type="primary" @click="onRxCancel()"> 处方撤销 </a-button>
              </div>
              <a-button v-if="tabActiveKey === '自费'" type="primary" class="ml-2" :disabled="!tableDataDetail.length" @click="onClickDiscounts(1)">
                批量打折
              </a-button>
            </div>
          </div>
          <!--tableDataDetail中 orderType  2:套餐明细  不可取消勾选 -->
          <BaseTable
            :loading="loading"
            column-code="00001108"
            :scroll="{ x: 1000 }"
            :height="getLeftTableHeight()"
            :data-source="tableDataDetail"
            row-key="id"
            bordered
            :row-selection="{
              selectedRowKeys: tableDetailId,
              onChange: onSelectChange,
              getCheckboxProps: (record) => ({
                disabled: record.orderType === '2'
              })
            }"
          >
            <template #bodyCell="{ column, index, record }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
              <template v-if="column.dataIndex === 'xmmc'">
                <template v-if="record.orderType === '1'">
                  <PopoverTable :width="800" :config="detailConfig" :params="{ jzbh, orderType: [2], tcid: record.tcid, cfbh: record.cfbh, yzzt: 1, jfzt: 0 }">
                    <template #bodyCell="{ column: popColumn, record: popRecord }">
                      <template v-if="popColumn.dataIndex === 'xmmc'">
                        <MedicineInfo :value="{ mc: popRecord.xmmc, gg: popRecord.gg, cj: popRecord.cj, insureStatus: record?.insureFlag }" />
                      </template>
                    </template>
                    {{ record?.xmmc }}
                  </PopoverTable>
                </template>
                <template v-else>
                  <MedicineInfo :value="{ mc: record?.xmmc, gg: record?.gg, cj: record?.cj, insureStatus: record?.insureFlag }" />
                </template>
              </template>
              <template v-if="column.dataIndex === 'yzzt'">
                <a-tag v-if="!+record.yzzt" color="green">正常</a-tag>
                <a-tag v-else color="red">失效</a-tag>
              </template>
              <template v-if="column.dataIndex === 'action'">
                <a-button type="link" size="small" @click="onClickDiscounts(record)"> 打折 </a-button>
              </template>
            </template>
          </BaseTable>
        </a-card>
        <div class="absolute w-full">
          <div v-if="showPrescription" class="overflow-auto overflow-x-hidden" style="max-height: 340px">
            <a-card v-for="(item, index) in prescriptionList" :key="index" class="mt-2 pb-4">
              <div class="flex mb-2">
                <BaseTitle class="!w-[150px] !mb-0" :title="'中药处方' + (index + 1) + '-加工'" />
                <div class="flex items-center">
                  <a-select v-model:value="item.drugStoreId" class="w-64" placeholder="请选择" :options="drugRoomList" />
                  <a-radio-group v-model:value="item.jzfs" class="ml-5" @change="onChangeRadio(item)">
                    <a-radio value="自煎">自煎</a-radio>
                    <a-radio value="代煎">代煎</a-radio>
                  </a-radio-group>
                </div>
              </div>
              <div class="w-full">
                <div class="flex mb-2">
                  <div class="mx-2">加工</div>
                  <div class="flex-1 cursor-pointer border-b-style min-w-80" @click="onClickProcessOpen(item)">
                    <a-input :value="generateProcess(item.processMethod)" readonly :bordered="false" class="w-full pt-0" placeholder="请选择加工方式" />
                  </div>
                  <div class="mx-2">加工费：￥{{ formatAmount(item.processMethod.processMethodCost) }}</div>
                  <BaseButton
                    :disabled="!item.processMethod.processMethodName"
                    type="text"
                    confirm-text="确认删除?"
                    danger
                    size="small"
                    @click="onDelCost(item, 'JGF')"
                    >删除</BaseButton
                  >
                </div>
                <div class="flex">
                  <div class="mx-2">快递</div>
                  <div class="flex-1 cursor-pointer border-b-style min-w-80" @click="onClickexpressOpen(item)">
                    <a-input :value="generateExpress(item.express)" readonly :bordered="false" class="w-full pt-0" placeholder="请输入快递信息" />
                  </div>
                  <div class="mx-2">快递费：￥{{ formatAmount(item.express.expressCost) }}</div>
                  <BaseButton :disabled="!item.express?.expressMode" confirm-text="确认删除?" type="text" danger size="small" @click="onDelCost(item, 'KD')">
                    删除
                  </BaseButton>
                </div>
              </div>
            </a-card>
          </div>
        </div>
      </div>

      <div class="w-2/5 flex flex-col h-full overflow-hidden">
        <a-card class="flex-1 overflow-auto">
          <BaseTitle title="收费类别" class="!mb-2.5" />
          <BaseTable :loading="loading" column-code="00001107" :data-source="tableDataType" bordered :height="getRightTableHeight()">
            <template #bodyCell="{ column, index }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
            </template>
            <template #footer>
              <div class="text-right w-full px-4">
                <template v-if="isCharge">
                  <span v-if="patientInfo.chargeStandardName"> ({{ patientInfo.chargeStandardName }})</span>
                </template>
                医疗费：<span class="text-xl font-bold text-red-500">￥{{ formatAmount(medicalPrice) }}</span>
              </div>
            </template>
          </BaseTable>
        </a-card>
        <div class="flex flex-col relative">
          <a-card v-if="tabActiveKey !== '自费' && tabActiveKey !== '特殊人员'" class="mt-2">
            <BaseTitle title="医保结算" class="!mb-0">
              <div class="flex">
                <span class="mr-1 font-normal">医保账户支付</span>
                <a-switch v-model:checked="formState.acctUsedFlag" class="mr-6" />
                <a-button type="primary" size="small" :disabled="!formState.brName" @click="onRxUpload()">预结算</a-button>
              </div>
            </BaseTitle>
            <div class="flex justify-between flex-wrap mt-2">
              <div class="w-1/2 mb-1">
                <span class="inline-block w-32 text-right">医疗总金额: </span>
                <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.ysje || 0) }}</span>
              </div>
              <div class="w-1/2 mb-1">
                <span class="inline-block w-32 text-right">账户余额: </span>
                <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.zhye || 0) }}</span>
              </div>
              <div class="w-1/2 flex items-center">
                <span class="inline-block w-32 text-right">医保支付: </span>
                <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.ybzf || 0) }}</span>
                <a-popover trigger="click">
                  <template #content>
                    <!-- <CHSPopover :data="preSettlementInfo.medicareAmountResponse" />  -->
                    <template v-if="readCardInfo.isgb">
                      <CHSPopover :data="preSettlementInfo.medicareAmountResponse" />
                    </template>
                    <template v-else>
                      <CHSWQPopover :data="preSettlementInfo.yb5AmountResponse" />
                    </template>
                  </template>
                  <a-button size="small" class="ml-2" shape="circle">
                    <span class="text-sm">?</span>
                  </a-button>
                </a-popover>
              </div>
              <div class="w-1/2">
                <span class="inline-block w-32 text-right">未贯标金额: </span>
                <span class="text-base">￥{{ formatAmount(preSettlementInfo.outPocketAmountResponse?.wgbje || 0) }}</span>
              </div>
            </div>
          </a-card>
          <a-card class="mt-2 w-full border-t flex-1">
            <div class="text-right">
              <div class="mb-2">
                本次应收 <span class="text-xl 2xl:text-3xl text-red-500 font-bold">￥{{ formatAmount(medicalPrice) }}</span>
              </div>
              <a-button class="ml-2 w-20 2xl:w-28" :size="isSmallScreen ? 'middle' : 'large'" @click="onClickReset">重置</a-button>
              <a-button
                type="primary"
                class="ml-2 w-20 2xl:w-28"
                :size="isSmallScreen ? 'middle' : 'large'"
                :loading="changeLoading"
                :disabled="!formState.brName"
                @click="onClickCharge"
              >
                收费
              </a-button>
            </div>
          </a-card>
        </div>
      </div>
    </div>
    <!-- <InsuranceOutModal v-model:open="chargeYbOpen" :register-price="categoryPrice" :charge-data="ybRegisterData" @success="onChargeSuccess" /> -->
    <ChargeModal
      v-model:open="chargeOpen"
      :br-id="formState.brId"
      :business-data="{ ...formState, ...preSettlementInfo }"
      :is-dispose="true"
      @success="onFetchCharge"
    />
    <ModalExpress v-model:open="expressOpen" :row-data="orderData.express" :br-id="formState.brId" @ok="onProcessOk" />
    <ModalProcess v-model:open="processOpen" :row-data="orderData.processMethod" @ok="onProcessOk" />
    <DiscountsOne v-model:open="discountsOneOpen" :row-data="projectRow" @success="onDiscountsSuccess" />
    <DiscountsMany v-model:open="discountsManyOpen" :discount-percent="discountPercent" :discounts-data="tableDataDetail" @success="onDiscountsSuccess" />
    <SelectRegisterModal v-model:open="openSelectModal" :resource-data="allRegisterData" @ok="onSelectRegister" />
    <!-- <a-modal v-model:open="testModel" title="test msg">
      <p>{{ testModelInfo }}</p>
    </a-modal> -->
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import BaseTitle from '@/components/BaseTitle'
import { formatAmount } from '@/utils/format.js'
import { post } from '@/utils/request'
import BaseTable from '@/components/BaseTable'
import ModalExpress from '@/components/ModalExpress'
import ModalProcess from '@/components/ModalProcess'
import { getSystemConfig } from '@/utils/systemConfig'
import ChargeModal from '@/components/ChargeModal'
import ReadCard from '@/components/ReadCard'
import DiscountsOne from './components/DiscountsOne'
import DiscountsMany from './components/DiscountsMany'
import SelectRegisterModal from './components/SelectRegisterModal.vue'

const loading = ref(false)
const jsonStr = ref('') //调用壳返回的JSON
const tabActiveKey = ref('自费') //选中的
const InAreaCode = ref('00') //00:国家医保101:上海医保 默认为 00
const chargeOpen = ref(false)
const showPrescription = ref(false)
const processOpen = ref(false)
const expressOpen = ref(false)
const discountsOneOpen = ref(false)
const discountsManyOpen = ref(false)
const isCoupon = ref(true)
const isCharge = ref(true)
const isCHS = ref(false)
const packageSwitch = ref(false)
const czFlag = ref(true)
const cfFlag = ref(true)
const cfbhData = ref([])
const cfbhList = ref([])
const tableDataType = ref([])
const tableDataDetail = ref([])
const patientInfo = ref({})
const tableDetailId = ref([])
const drugRoomList = ref([])
const prescriptionList = ref([])
const projectRow = ref({})
const orderData = ref({})
const jzbh = ref('')
const medicalPrice = ref(0) // 应收金额
const deposit = ref('')
const depositPrice = ref(0) // 押金金额
const discountPercent = ref(0)
const couponId = ref(null) // 抵用券id
const couponPrice = ref('') // 抵用券金额
const memberId = ref('') // 会员id
const memberPrice = ref('') // 会员卡钱
const readCardRef = ref(null)
const allRegisterData = ref([])
const openSelectModal = ref(false)
const formState = ref({
  stdate: dayjs().format('YYYY-MM-DD'),
  eddate: dayjs().format('YYYY-MM-DD'),
  settlementType: true, //是否医保结算
  acctUsedFlag: true //是否医保账户支付
})
const readCardInfo = ref({}) //读卡信息
const readSuccess = (val) => {
  if (!val.brId) return message.error('当前患者未登记')
  readCardInfo.value = val
  formState.value.brId = val.brId
  formState.value.brName = val.brName
  getUserInfo()
}
const tabChange = (val) => {
  tabActiveKey.value = val
  onClickReset()
}
const preSettlementInfo = ref({})
const getUserInfo = async () => {
  const res = await post('/outp/mzdj/getOutpRecordInfoList', {
    pyjm: '',
    stdate: tabActiveKey.value === '特殊人员' ? undefined : formState.value.stdate,
    eddate: tabActiveKey.value === '特殊人员' ? undefined : formState.value.eddate,
    type: '2',
    brId: formState.value.brId,
    cxtype: tabActiveKey.value === '特殊人员' ? 'zf' : 'yb'
  })
  if (res.code !== 0) return message.error(res.msg)
  if (res.data?.length > 0) {
    if (res.data?.length > 1) {
      allRegisterData.value = res.data
      openSelectModal.value = true
      return
    } else {
      onSelectRegister(res.data[0])
    }
  } else {
    formState.value.brId = ''
    formState.value.brName = ''
    message.warn('暂无待缴费患者')
  }
}

const onSelectRegister = (select) => {
  patientInfo.value = select || {}
  if (select?.jzbh) {
    jzbh.value = select?.jzbh
    formState.value.medTypeName = select?.medTypeName
    formState.value.insutypeName = select?.insutypeName
    formState.value.insutype = select?.insutype
    formState.value.brName = select?.brName
    deposit.value = ''
    couponId.value = ''
    memberId.value = ''
    memberPrice.value = ''
    couponPrice.value = ''
  } else {
    formState.value.brId = ''
    formState.value.brName = ''
    message.warn('暂无待缴费患者')
  }
}

const getLeftTableHeight = () => {
  const topHeight = tabActiveKey.value !== '自费' ? 400 : 365
  let height = window.innerHeight - topHeight + (isCHS.value ? 10 : 10)
  if (prescriptionList.value.length === 1 && showPrescription.value) {
    height = window.innerHeight - topHeight - 150
  }
  if (prescriptionList.value.length > 1 && showPrescription.value) {
    height = window.innerHeight - topHeight - 310
  }
  return height
}
const getRightTableHeight = () => {
  const topHeight = tabActiveKey.value !== '自费' ? '660' : '530'
  const tableHeight = window.innerHeight - topHeight
  return tableHeight < 240 ? 240 : tableHeight
}
const onSelect = async (select) => {
  formState.value.brName = select.brName
  formState.value.brId = select.brId
  jzbh.value = select.jzbh
  deposit.value = ''
  couponId.value = ''
  memberId.value = ''
  memberPrice.value = ''
  couponPrice.value = ''
  await getOutpInfo()
}

// 获取患者信息
const getOutpInfo = async () => {
  const { code, data, msg } = await post('/outp/mzys/getOutpRecordInfo', { mzjlbh: jzbh.value })
  if (code !== 0) return message.error(msg || '获取信息失败')
  patientInfo.value = data
}

// 单项
const onClickDiscounts = async (row) => {
  if (row === 1) {
    discountsManyOpen.value = true
  } else {
    projectRow.value = { ...row }
    discountsOneOpen.value = true
  }
}
const detailConfig = ref({
  url: '/outp/oupCharge/getOutpClinicalOrderInfoList',
  columnCode: '00001190',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      NO: index + 1
    }))
  }
})

const getFeeCategoryList = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getOutpClinicalOrderTypeList', { jzbh: jzbh.value, yzzt: 1, ids: tableDetailId.value })
  if (code !== 0) return message.error(msg)
  tableDataType.value = data
}

const chargeDetailList = async () => {
  const {
    code,
    data = [],
    msg
  } = await post('/outp/oupCharge/getOutpClinicalOrderInfoList', {
    jzbh: jzbh.value,
    orderType: packageSwitch.value ? [0, 1] : [0, 2],
    yzzt: 1,
    jfzt: 0,
    jfztList: ['0', '3'],
    czFlag: czFlag.value ? 1 : 0,
    cfFlag: cfFlag.value ? 1 : 0,
    cfbhList: cfbhList.value
  })
  if (code !== 0) return message.error(msg)
  tableDataDetail.value = data
  tableDetailId.value = data.map((item) => item.id)
  getReceiptsCount()
}

const getReceiptsCount = async () => {
  showPrescription.value = tableDataDetail.value.some((item) => item.lbmc === '中药费')
  await getPrescription()
}

const getPrescription = async () => {
  const res = await post('/outp/outpClinicalOrder/getOutpTCMHeadList', { jzbh: [jzbh.value], jksy: 1 })
  if (res.code !== 0) return message.error(res.msg)
  prescriptionList.value = res.data
  // getReceiptsAmount()
}
const onSelectChange = (selectedRowKeys) => {
  tableDetailId.value = selectedRowKeys
  getFeeCategoryList()
  getAmount()
}
const getAmount = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getOutpClinicalOrderInfoTotalCost', { jzbh: jzbh.value, ids: tableDetailId.value })
  if (code !== 0) return message.error(msg)
  medicalPrice.value = data
  formState.value.ysje = data
  // receivablePrice.value = data
  // if (depositPrice.value !== 0) {
  //   medicalPrice.value = receivablePrice.value - depositPrice.value
  // }
  // getReceiptsAmount()
}
const getDrugRooms = async () => {
  const res = await post('/operation/opex/getDrugStoreInfoList', { status: 1 })
  if (res.code !== 0) return message.error(res.msg)
  drugRoomList.value = res.data.map((item) => {
    return { label: item.storeName, value: item.id }
  })
}

const onChangeRadio = async (row) => {
  orderData.value = row
  if (row.jzfs === '自煎') {
    row.processMethod = { processMethodCost: 0 }
  } else {
    row.processMethod = orderData.value.processMethod
  }
  await onSaveMedicineList()

  // getReceiptsAmount()
}

const generateProcess = (processMethod = {}) => {
  if (!processMethod.processMethodName) return ''
  return `${processMethod.processMethodName} ${processMethod.processMethodCmemo || ''}`
}
const generateExpress = (express = {}) => {
  if (!express.expressMode) return ''
  return `【${express.expressMode || ''}】${express.contactName || ''}，${express.contactPhone || ''}，${express.provinceName || ''}${express.cityName || ''}${
    express.countyName || ''
  }${express.addressDetail || ''} ${express.expressCmemo || ''}`
}
//获取快递信息
const onClickexpressOpen = async (row) => {
  orderData.value = row
  if (orderData.value.express.isUseOneAddress) return message.warning('默认处方1地址无法修改')
  expressOpen.value = true
}
const onClickProcessOpen = (row) => {
  orderData.value = row
  if (row.jzfs === '代煎') {
    processOpen.value = true
  }
}
const onProcessOk = async (row) => {
  if (row.processMethodName) {
    orderData.value.processMethod = row
  } else {
    orderData.value.express = row
  }
  const findState = prescriptionList.value.findIndex((x) => x.drugStoreId === orderData.value.drugStoreId)
  if (findState !== -1) {
    prescriptionList.value.splice(findState, 1, orderData.value)
  }
  await onSaveMedicineList()
}

const onDiscountsSuccess = async (params) => {
  const { code, msg } = await post('/outp/oupCharge/outpClinicalDiscount', { ...params, sfzsmx: packageSwitch.value ? 0 : 1 })
  if (code !== 0) return message.error(msg)
  discountsOneOpen.value = false
  message.success(msg)
  await chargeDetailList()
  getFeeCategoryList()
  getAmount()
}

const onSaveMedicineList = () => {
  prescriptionList.value.forEach(async (item) => {
    const params = {
      keycode: jzbh.value,
      ...item
    }
    const { code, msg } = await post('/outp/outpClinicalOrder/doSaveOutpTCMHead', params)
    if (code !== 0) return message.error(msg || '操作失败')
    getFeeCategoryList()
    getAmount()
  })
}

const onPrint = async (item = {}) => {
  if (getSystemConfig('PRINT_INVOICE_AFTER_CHARGE') === '0') return
  const { code, msg, data } = await post('/outp/oupCharge/PrintMedicareCharges', { jzbh: jzbh.value, pjhm: item.pjhm, sftfbs: '0' })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

const onClickReset = () => {
  formState.value = {
    settlementType: true,
    acctUsedFlag: true,
    stdate: dayjs().format('YYYY-MM-DD'),
    eddate: dayjs().format('YYYY-MM-DD')
  }
  readCardRef.value?.reset()
  jzbh.value = ''
  preSettlementInfo.value = {}
  prescriptionList.value = []
  depositPrice.value = 0
  deposit.value = ''
  patientInfo.value = {}
  tableDataType.value = []
  tableDataDetail.value = []
  tableDetailId.value = []
  cfbhData.value = []
  cfbhList.value = []
  packageSwitch.value = false
  czFlag.value = true
  cfFlag.value = true
}
const onClickRefresh = async () => {
  await chargeDetailList()
  getFeeCategoryList()
  getAmount()
}
const onChangeCfSwitch = async (e) => {
  if (!e) {
    cfbhData.value = []
    cfbhList.value = []
  } else {
    await getCfData()
  }
  await chargeDetailList()
  getFeeCategoryList()
  getAmount()
}
const getCfData = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getOutpClinicalCfbhInfoList', {
    jzbh: jzbh.value,
    orderType: packageSwitch.value ? [0, 1] : [0, 2],
    yzzt: 1,
    jfzt: 0,
    jfztList: ['0', '3']
  })
  if (code !== 0) return message.error(msg)
  if (data && data.length > 0) {
    cfbhData.value = data.map((item) => {
      return { label: item.cfmc, value: item.cfbh }
    })
    cfbhList.value = data.map((item) => {
      return item.cfbh
    })
  } else {
    cfbhData.value = []
  }
}

const onClickCharge = async () => {
  if (tabActiveKey.value === '自费' || tabActiveKey.value === '特殊人员' || !formState.value.settlementType) {
    if (tabActiveKey.value === '特殊人员') {
      const res = await post('/outp/oupCharge/obtainExpenseRetiredCadres', {
        obtainExpenseMzRequest: {
          jzbh: jzbh.value,
          yzId: tableDetailId.value
        },
        retiredCadreType: readCardInfo.value.retiredCadreType,
        retiredCadre: readCardInfo.value.retiredCadre,
        type: 'MZ'
      })
      if (res.code !== 0) return message.error(res.msg || '收费失败')
      preSettlementInfo.value = {
        ysje: res.data?.ysje,
        outPocketAmountResponse: {
          ssje: res.data?.ssje,
          ybzf: res.data?.ybzf
        }
      }
    }
    //自费
    const { code, msg } = await post('/outp/oupCharge/doCheckClinicalOrdersIsSign', {
      ids: tableDetailId.value
    })
    if (code !== 0) return message.error(msg)
    if (!Number(formatAmount(formState.value.ysje))) {
      formatZeroMoney()
    } else {
      formState.value.deposit = deposit.value
      chargeOpen.value = true
    }
  } else {
    //医保 - 处方上传
    onRxUpload(true)
  }
}
const formatZeroMoney = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  const chargeData = {}
  if (data && data.length > 0) {
    data.forEach((item) => {
      chargeData[item.zffsdm] = chargeData[item.zffsdm] ? chargeData[item.zffsdm] : 0
    })
  }
  chargeData.change = 0
  chargeData.fbyh = 0
  chargeData.yhje = 0
  chargeData.ysje = '0.00'
  chargeData.ssje = '0.00'
  onFetchCharge(chargeData)
}

watch(
  () => jzbh.value,
  async () => {
    await getCfData()
    await chargeDetailList()
    getFeeCategoryList()
    getAmount()
    getDrugRooms()
  }
)

watch(
  () => deposit.value,
  () => {
    depositPrice.value = 0
  }
)
const isSmallScreen = window.screen.availWidth < 1600 //是否小屏

onMounted(() => {
  isCoupon.value = getSystemConfig('ENABLE_REGISTER_DISCOUNT') === '1' //启用挂号优惠功能
  isCharge.value = getSystemConfig('ENABLE_CHARGE_STANDARD_MODE') === '1' //收费标准
  isCHS.value = getSystemConfig('IS_EXIST_MEDICAL_INSURANCE') === '1' //是否启用医保
  InAreaCode.value = getSystemConfig('NMI_REGION_CODE') //00:国家医保101:上海医保 默认为 00
  // getInsuranceInfo()
})

/*
 * 2024-08-15 新增
 * 收费功能重构
 * 流程 1.处方上传 2.弹出收费界面（收费方式，优惠） 3.收费
 */
const changeLoading = ref(false)
// 处方上传
const onRxUpload = async (isOpen = false, times = 3, type = '', action = '') => {
  if (!jzbh.value) return message.error('无就诊编号')
  const res = await post(
    '/outp/oupCharge/outpPreSettlementPrescriptions',
    {
      jzbh: jzbh.value,
      mdtrtCertNo: readCardInfo.value.mdtrt_cert_no,
      mdtrtCertType: readCardInfo.value.mdtrt_cert_type,
      psn_no: readCardInfo.value.psn_no,
      ybkh: readCardInfo.value.kh,
      yzId: tableDetailId.value,
      jsonStr: jsonStr.value,
      zhbs: readCardInfo.value.isgb ? undefined : readCardInfo.value?.ybkResonse?.zhbs,
      type: type
    },
    {
      loading: true
    }
  )
  if (res.code !== 0) return message.error(res.msg || '处方上传失败')
  if (action === 'upload') message.success('处方上传成功')
  if (readCardInfo.value.isgb) {
    chargeOpen.value = isOpen
    preSettlementInfo.value = res.data
  } else {
    let result = window.openExe?.readGHQQ(res.data?.jsonStr)
    if (!window.openExe) {
      if (res.data.type === 'YJS') {
        result =
          '{"response":{"jysj":"2022-06-28 13:01:55","xxlxm":"SN01","xxfhm":"P001","fhxx":"","bbh":"0001","msgid":"Y021010030020220628000830208","xzqhdm":"310000","jgdm":"Y0210100300","czybm":"001","czyxm":"李倩雯","xxnr":{"mxzdh":"MZ202206280205514843","mxxms":[{"xh":"1","clbz":"0","fhxx":"","bxbz":"0","mxxmje":"10","mxxmjyfy":"5","mxxmybjsfwfy":"5"}]},"jyqd":"10","jyyzm":"","zdjbhs":""}}'
      } else if (res.data.type === 'SCCF') {
        result =
          '{"response":{"czybm":"001","sysResv":"1234567887654321WvHPvHPWWHvPHPWvPvWHWWvPHWPPvvHPHWvPc0a8006f","recvTime":"0004089798fc01fd","bbh":"0001","msgid":"Y021010030020220628000830200","fhxx":"","jyqd":"10","xxlxm":"SN02","jyyzm":"","xzqhdm":"310000","jysj":"2022-06-28 12:43:16","jgdm":"Y0210100300","xxfhm":"P001","zdsbsbm":"","czyxm":"李倩雯","xxnr":{}}}'
      } else if (res.data.type === 'JS') {
        result =
          '{"response":{"czybm":"001","sysResv":"1234567887654321WvHPvHPWWHvPHPWvPvWHWWvPHWPPvvHPHWvPc0a8006f","recvTime":"0004089798fc01fd","bbh":"0001","msgid":"Y021010030020220628000830200","fhxx":"","jyqd":"10","xxlxm":"SI11","jyyzm":"","xzqhdm":"310000","jysj":"2022-06-28 12:43:16","jgdm":"Y0210100300","xxfhm":"P001","zdsbsbm":"","czyxm":"李倩雯","xxnr":{"fjdzhzfs":"0.00","jlc":"300003757604","zfdxjzfs":"0.00","tcdxjzfs":"0.00","totalexpense":"10","jfje":"0","zfdlnzhzfs":"0.00","curaccountpay":"0.00","tczfs":"0.00","curaccountamt":"0.00","fjdxjzfs":"5","fjzfs":"5","cardid":"N02423258","accountattr":"1000000000000000","tcdzhzfs":"0.00","cardtype":"1","fybjsfwfyze":"5","jssqxh":"I12Y021010030010430210628141867396","hisaccountamt":"0.00","ybjsfwfyze":"10","hisaccountpay":"0.00","personname":"吕琦华","personspectag":"0"}}}'
      } else {
        result =
          '{"response":{"czybm":"001","sysResv":"1234567887654321UeS6eS6UUSe6S6Ue6eUSUUe6SU66eeS6SUe6c0a8006f","recvTime":"0004089798fc01fd","bbh":"0001","msgid":"Y021010030020220628000830194","fhxx":"","jyqd":"10","xxlxm":"SH01","jyyzm":"","xzqhdm":"310000","jysj":"2022-06-28 12:06:14","jgdm":"Y0210100300","xxfhm":"P001","zdsbsbm":"","czyxm":"李倩雯","xxnr":{"fjdzhzfs":"0.00","jlc":"300003757604","zfdxjzfs":"0.00","tcdxjzfs":"0.00","totalexpense":"9.00","jfje":"0","zfdlnzhzfs":"0.00","curaccountpay":"0.00","tczfs":"0.00","curaccountamt":"0.00","fjdxjzfs":"3.15","fjzfs":"5.85","cardid":"N02423258","jmjsbz":"0","accountattr":"1000000000000000","tcdzhzfs":"0.00","cardtype":"1","fybjsfwfyze":"1.00","jssqxh":"H02Y021010030010430210628141799545","hisaccountamt":"0.00","ybjsfwfyze":"9.00","hisaccountpay":"0.00","personname":"吕琦华","personspectag":"0"}}}'
      }
    }
    const res1 = await post(
      'outp/mzdj/doCallbackAPi',
      {
        jsonStr: result,
        jzbh: jzbh.value,
        type: res.data.type,
        mxzdh: res.data.mxzdh,
        yzId: res.data.type === 'JS' ? tableDetailId.value : undefined
      },
      {
        loading: true
      }
    )
    if (res1.code !== 0) return message.error(res1.msg || '收费失败')
    if (res1.data?.isNext === '1' && times <= 0) return message.error('收费失败')
    if (res1.data?.isNext === '1') {
      //循环调用，自多调用三次
      onRxUpload(isOpen, times--, res.data.type)
    } else {
      chargeOpen.value = isOpen
      preSettlementInfo.value = res1.data
    }
  }
}
// 处方撤销
const onRxCancel = async () => {
  const res = await post(
    '/outp/oupCharge/outpatientFeeRevocation',
    {
      jzbh: jzbh.value
    },
    { loading: true }
  )
  if (res.code !== 0) return message.error(res.msg || '处方撤销失败')
  // 0:自费 1:五期 2:国家医保
  if (patientInfo.value?.miFlag === 2) {
    window.openExe?.readCFCX(res.data?.jsonStr)
    message.success(res.msg || '处方撤销成功')
  } else if (patientInfo.value?.miFlag === 1) {
    let result = window.openExe?.readGHQQ(res.data?.jsonStr)
    if (!window.openExe) {
      if (res.data.type === 'YJS') {
        result =
          '{"response":{"jysj":"2022-06-28 13:01:55","xxlxm":"SN01","xxfhm":"P001","fhxx":"","bbh":"0001","msgid":"Y021010030020220628000830208","xzqhdm":"310000","jgdm":"Y0210100300","czybm":"001","czyxm":"李倩雯","xxnr":{"mxzdh":"MZ202206280205514843","mxxms":[{"xh":"1","clbz":"0","fhxx":"","bxbz":"0","mxxmje":"10","mxxmjyfy":"5","mxxmybjsfwfy":"5"}]},"jyqd":"10","jyyzm":"","zdjbhs":""}}'
      } else if (res.data.type === 'SCCF') {
        result =
          '{"response":{"czybm":"001","sysResv":"1234567887654321WvHPvHPWWHvPHPWvPvWHWWvPHWPPvvHPHWvPc0a8006f","recvTime":"0004089798fc01fd","bbh":"0001","msgid":"Y021010030020220628000830200","fhxx":"","jyqd":"10","xxlxm":"SN02","jyyzm":"","xzqhdm":"310000","jysj":"2022-06-28 12:43:16","jgdm":"Y0210100300","xxfhm":"P001","zdsbsbm":"","czyxm":"李倩雯","xxnr":{}}}'
      } else if (res.data.type === 'JS') {
        result =
          '{"response":{"czybm":"001","sysResv":"1234567887654321WvHPvHPWWHvPHPWvPvWHWWvPHWPPvvHPHWvPc0a8006f","recvTime":"0004089798fc01fd","bbh":"0001","msgid":"Y021010030020220628000830200","fhxx":"","jyqd":"10","xxlxm":"SI11","jyyzm":"","xzqhdm":"310000","jysj":"2022-06-28 12:43:16","jgdm":"Y0210100300","xxfhm":"P001","zdsbsbm":"","czyxm":"李倩雯","xxnr":{"fjdzhzfs":"0.00","jlc":"300003757604","zfdxjzfs":"0.00","tcdxjzfs":"0.00","totalexpense":"10","jfje":"0","zfdlnzhzfs":"0.00","curaccountpay":"0.00","tczfs":"0.00","curaccountamt":"0.00","fjdxjzfs":"5","fjzfs":"5","cardid":"N02423258","accountattr":"1000000000000000","tcdzhzfs":"0.00","cardtype":"1","fybjsfwfyze":"5","jssqxh":"I12Y021010030010430210628141867396","hisaccountamt":"0.00","ybjsfwfyze":"10","hisaccountpay":"0.00","personname":"吕琦华","personspectag":"0"}}}'
      } else {
        result =
          '{"response":{"czybm":"001","sysResv":"1234567887654321UeS6eS6UUSe6S6Ue6eUSUUe6SU66eeS6SUe6c0a8006f","recvTime":"0004089798fc01fd","bbh":"0001","msgid":"Y021010030020220628000830194","fhxx":"","jyqd":"10","xxlxm":"SH01","jyyzm":"","xzqhdm":"310000","jysj":"2022-06-28 12:06:14","jgdm":"Y0210100300","xxfhm":"P001","zdsbsbm":"","czyxm":"李倩雯","xxnr":{"fjdzhzfs":"0.00","jlc":"300003757604","zfdxjzfs":"0.00","tcdxjzfs":"0.00","totalexpense":"9.00","jfje":"0","zfdlnzhzfs":"0.00","curaccountpay":"0.00","tczfs":"0.00","curaccountamt":"0.00","fjdxjzfs":"3.15","fjzfs":"5.85","cardid":"N02423258","jmjsbz":"0","accountattr":"1000000000000000","tcdzhzfs":"0.00","cardtype":"1","fybjsfwfyze":"1.00","jssqxh":"H02Y021010030010430210628141799545","hisaccountamt":"0.00","ybjsfwfyze":"9.00","hisaccountpay":"0.00","personname":"吕琦华","personspectag":"0"}}}'
      }
    }
    const res1 = await post(
      'outp/mzdj/doCallbackAPi',
      {
        jsonStr: result,
        jzbh: jzbh.value,
        type: res.data.type,
        mxzdh: res.data.mxzdh,
        yzId: res.data.type === 'JS' ? tableDetailId.value : undefined
      },
      {
        loading: true
      }
    )
    if (res1.code !== 0) return message.error(res1.msg || '处方撤销失败')
    message.success(res.msg || '处方撤销成功')
  }
}

const onFetchCharge = async (chargeData = {}) => {
  if (tabActiveKey.value === '自费' || tabActiveKey.value === '特殊人员' || !formState.value.settlementType) {
    changeLoading.value = true
    const { code, msg, data } = await post(
      chargeData.zffs === '2' ? '/outp/oupCharge/doPaymentForScan' : '/outp/oupCharge/doSaveOutPFee',
      {
        ...chargeData,
        ybje: chargeData?.ybzf || 0,
        sflb: 'MZ',
        ids: tableDetailId.value,
        jzbh: jzbh.value,
        yjdh: deposit.value,
        retiredCadreType: readCardInfo.value?.retiredCadreType, // 类别
        retiredCadre: readCardInfo.value?.retiredCadre, // 退休干部
        miFlag: 0,
        sfzsmx: packageSwitch.value ? 0 : 1
      },
      {
        loading: true,
        timeout: 2 * 60 * 1000 // 超时时间2分钟
      }
    )
    if (code !== 0) {
      changeLoading.value = false
      return message.error(msg)
    }
    changeLoading.value = false
    message.success(msg)
    chargeOpen.value = false
    onPrint(data)
    onClickReset()
  } else {
    //医保支付
    // formState.value.insutype
    //阜阳医保才会调壳验证密码
    let verRes = ''
    if (getSystemConfig('NMI_REGION_CODE') === '022' && formState.value.insutype === '310' && tabActiveKey.value === '社保卡') {
      verRes = await window.openExe?.iVerifyPIN()
    }
    changeLoading.value = true
    const { code, msg, data } = await post(
      '/outp/oupCharge/outpPaymentForScanZF',
      {
        ...chargeData,
        sflb: 'MZ',
        ids: tableDetailId.value,
        jzbh: jzbh.value,
        yjdh: deposit.value,
        miFlag: 0,
        sfzsmx: packageSwitch.value ? 0 : 1,
        pjhm: preSettlementInfo.value.outPocketAmountResponse?.pjhm,
        insureStatus: 1,
        acct_used_flag: formState.value.acctUsedFlag ? '1' : '0',
        healthCareRegisteredData: readCardInfo.value, //读卡医保信息
        medicareSettlementInfo: {
          //预结算信息
          ...preSettlementInfo.value.outPocketAmountResponse,
          ...preSettlementInfo.value.medicareAmountResponse
        },
        zhbs: readCardInfo.value.isgb ? undefined : readCardInfo.value?.ybkResonse?.zhbs,
        mmJson: verRes ? verRes : undefined
      },
      {
        loading: true
      }
    )
    if (code !== 0) {
      changeLoading.value = false
      return message.error(msg)
    }
    if (readCardInfo.value.isgb) {
      changeLoading.value = false
      message.success(msg)
      chargeOpen.value = false
      if (data && data.length > 0) {
        data.forEach((item) => {
          onPrint(item)
        })
      }
      onClickReset()
    } else {
      let result = window.openExe?.readGHQQ(data)
      if (!window.openExe) {
        result =
          '{"response":{"czybm":"001","sysResv":"1234567887654321c82c82ccc28c2cc8c8c2cc8c2ccc882c2c8cc0a8006f","recvTime":"0004089798fc01fd","bbh":"0001","msgid":"Y021010030020220628000830202","fhxx":"","jyqd":"10","xxlxm":"SI12","jyyzm":"","xzqhdm":"310000","jysj":"2022-06-28 12:43:19","jgdm":"Y0210100300","xxfhm":"P001","zdsbsbm":"","czyxm":"李倩雯","xxnr":{"fjdzhzfs":"0.00","jlc":"300003757604","lsh":"2101010287599771","zfdxjzfs":"0.00","tcdxjzfs":"0.00","totalexpense":"10","jfje":"","zfdlnzhzfs":"0.00","curaccountpay":"0.00","tczfs":"0.00","curaccountamt":"0.00","fjdxjzfs":"5","fjzfs":"5","cardid":"N02423258","tcdzhzfs":"0.00","cardtype":"1","fybjsfwfyze":"5","jssqxh":"I12Y021010030010430210628141867396","hisaccountamt":"0.00","ybjsfwfyze":"661.08","hisaccountpay":"0.00"}}}'
      }
      const res1 = await post(
        'outp/mzdj/doCallbackAPi',
        {
          jsonStr: result,
          outPFeeType: {
            ...chargeData,
            sflb: 'MZ',
            ids: tableDetailId.value,
            jzbh: jzbh.value,
            yjdh: deposit.value,
            miFlag: 0,
            sfzsmx: packageSwitch.value ? 0 : 1,
            pjhm: preSettlementInfo.value.outPocketAmountResponse?.pjhm,
            insureStatus: 1,
            healthCareRegisteredData: readCardInfo.value, //读卡医保信息
            medicareSettlementInfo: {
              //预结算信息
              ...preSettlementInfo.value.outPocketAmountResponse,
              ...preSettlementInfo.value.medicareAmountResponse
            }
          }
        },
        {
          loading: true
        }
      )
      if (res1.code !== 0) return message.error(res1.msg)
      changeLoading.value = false
      message.success(res1.msg)
      chargeOpen.value = false
      if (res1.data && res1.data.length > 0) {
        res1.data.forEach((item) => {
          onPrint(item)
        })
      }
      onClickReset()
    }
  }
}
const onDelCost = async (item, xdFlag) => {
  const { code, msg } = await post('/outp/outpClinicalOrder/doDelTcmExtraCost', { cfdh: item.cfdh, xdFlag })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  onClickRefresh()
}
</script>
<style lang="less" scoped>
:deep(.ant-radio-button-wrapper) {
  flex: 1;
  color: var(--primary-color);
  text-align: center;
  border-color: var(--primary-color);
  &::before {
    background-color: var(--primary-color);
  }
}
.order-footer {
  @apply cursor-pointer border-b py-1;
}
:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}
.discount-input {
  :deep(.ant-input) {
    text-align: right;
  }
}
.color-placeholder {
  color: var(--disabled-text-color);
}
:deep(.border-b-style) {
  border-bottom: 1px solid var(--border-color) !important;
  // border-bottom: 1px solid transparent;
  border-radius: 0;
  input {
    cursor: pointer !important;
  }
  &:hover {
    border-bottom: 1px solid var(--primary-color) !important;
  }
}
</style>
